package com.dikang.keer.wms.service.impl;

import com.dikang.common.constant.WareConstant;
import com.dikang.keer.wms.entity.PurchaseDetailEntity;
import com.dikang.keer.wms.feign.ProductFeignService;
import com.dikang.keer.wms.service.PurchaseDetailService;
import com.dikang.keer.wms.service.WareSkuService;
import com.dikang.keer.wms.vo.MergeVo;
import com.dikang.keer.wms.vo.PurchaseDoneVo;
import com.dikang.keer.wms.vo.PurchaseItemDoneVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dikang.common.utils.PageUtils;
import com.dikang.common.utils.Query;

import com.dikang.keer.wms.dao.PurchaseDao;
import com.dikang.keer.wms.entity.PurchaseEntity;
import com.dikang.keer.wms.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {
    @Autowired
    private PurchaseDetailService purchaseDetailService;
    @Autowired
    private WareSkuService wareSkuService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryUnReceiverPage(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("status",WareConstant.PurchaseStatusEnum.CREATED).or().eq("status",WareConstant.PurchaseStatusEnum.ASSIGNED.getCode());
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),wrapper

        );

        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void mergePurchase(MergeVo mergeVo) {
        PurchaseEntity purchase = new PurchaseEntity();
        purchase.setId(mergeVo.getPurchaseId());
        // 如果没有传递purchaseId的话创建新的采购单
        if (mergeVo.getPurchaseId()==null){
            purchase.setPriority(0);
            purchase.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            baseMapper.insert(purchase);

            // 把需求假如到订单
        }else {
            // 确认采购单状态为 0或者1才能合并
            Integer status = this.getById(mergeVo.getPurchaseId()).getStatus();
            if (!status.equals(WareConstant.PurchaseStatusEnum.ASSIGNED.getCode())&&!status.equals(WareConstant.PurchaseStatusEnum.CREATED.getCode())){
                log.info("采购单非新建或分配状态");
               throw new RuntimeException("采购单非新建或分配状态");
            }
            purchase.setStatus(WareConstant.PurchaseStatusEnum.ASSIGNED.getCode());
            this.saveOrUpdate(purchase);
        }

        // 把需求加入到采购单中
        Long[] items = mergeVo.getItems();
        if (items!=null&&items.length>0){
      for (Long item : items) {
        //
          PurchaseDetailEntity purchaseDetail = purchaseDetailService.getById(item);
          purchaseDetail.setPurchaseId(purchase.getId());
          purchaseDetail.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
          purchaseDetailService.saveOrUpdate(purchaseDetail);
      }
        }

    }

    @Override
    @Transactional
    public void receiver(List<Long> ids) {
        // TODO 判断是否领取自己的采购单 用request获取出他的memberId和请求单上的received中的memberId比较
       ids.stream().map((item) -> {
            // 查询出采购单信息并且判断采购单状态是否已分配状态
            PurchaseEntity purchaseEntity = this.getById(item);
            if (purchaseEntity.getStatus().equals(WareConstant.PurchaseStatusEnum.ASSIGNED.getCode())) {
                // 修改采购单和的状态
                purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
                this.updateById(purchaseEntity);
                // 修改采购需求的状态
                QueryWrapper<PurchaseDetailEntity> wrapper = new QueryWrapper<>();
                List<PurchaseDetailEntity> details = purchaseDetailService.list(wrapper.eq("purchase_id", item));
                List<PurchaseDetailEntity> detailEntityList = details.stream().map((detail) -> {
                    detail.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                    return detail;
                }).filter((d)->{ return d.getStatus()==WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode();}).collect(Collectors.toList());
                purchaseDetailService.updateBatchById(detailEntityList);
            }
            return null;

        }).collect(Collectors.toList());



    }

    /** 完成采购
     *
     * @param doneVo
     */
    @Override
    public void purchaseDone(PurchaseDoneVo doneVo) {
        //根据采购需求状态来判断订单是否完成状态
        Long purchaseId = doneVo.getId();
        PurchaseEntity purchase = this.getById(purchaseId);
        List<PurchaseItemDoneVo> items = doneVo.getItems();
        // 是否异常
        boolean flag = true;
        int finish =0;
        List<PurchaseDetailEntity> purchaseDetail = new ArrayList<>();
        for (PurchaseItemDoneVo item : items) {
            PurchaseDetailEntity purchaseDetailEntity = purchaseDetailService.getById(item.getItemId());
            // 如果有一个采购不成功的话改变其采购单和需求状态为异常
        if (item.getStatus()==WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()){
            flag = false;
            purchaseDetailEntity.setStatus(item.getStatus());
        }
        else{
            finish++;
            purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
            // TODO 加库存
            wareSkuService.addStock(purchaseDetailEntity.getSkuId(),purchaseDetailEntity.getWareId(),purchaseDetailEntity.getSkuNum());



        }
        purchaseDetail.add(purchaseDetailEntity);
    }
        // 如果这个采购单下的所有需求都成功了改变其状态为成功
        purchaseDetailService.saveBatch(purchaseDetail);
        //  判断是否所有需求都采购成功
        int count = purchaseDetailService.count(new QueryWrapper<PurchaseDetailEntity>().eq("purchase_id", purchaseId));
        int finishPurchase = purchaseDetailService.count(new QueryWrapper<PurchaseDetailEntity>().eq("purchase_id", purchaseId).eq("status",WareConstant.PurchaseDetailStatusEnum.FINISH.getCode()));
        int finishCount =finishPurchase+finish;
        if (finishCount==count){
            purchase.setStatus(WareConstant.PurchaseStatusEnum.FINISH.getCode());
        }else if (flag){
            purchase.setStatus(WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        }
        this.saveOrUpdate(purchase);

    }


}